from py2neo import Graph, Node, Relationship, RelationshipMatcher, NodeMatcher
import random

graph = Graph("bolt://localhost:7687", auth=("neo4j", "12345678"))

def recommend_movie(movie_title):
    # 找到要查找的movie的type节点
    type_ = graph.run(f"MATCH (a:movie)-[r:type]->(b) WHERE a.name = '{movie_title}' RETURN a, b")
    type_b = []
    for item in type_:
        type_b.append(item.get('b'))
    #找出来的电影找上下五年top-K的
    movie_year = int(item.get('a')['year'])
    # print(movie_year) 2017
    # [Node('type', name='动作'), Node('type', name='犯罪'), Node('type', name='悬疑')]
    # print(type_b)
    top_movie = []
    for temp in type_b:
        movie_type = temp['name']
        top_movie.append(find_top_5_movie(movie_type, movie_year))
    # print(top_movie)
    list_top_movie = []
    for item in top_movie:
        list_top_movie += item
    result = random.sample(list_top_movie, 5)
    print(result)
    # for i in result:
    #     print(i['name'])
    return result

def find_top_5_movie(movie_type, movie_year):
    movie_result = list(graph.run(f"MATCH(a: movie)-[: type]->(b:type) WHERE b.name IN ['{movie_type}'] RETURN a"))
    # 读取不同类型中的电影名字，评分，评星，为后续推荐提供数据
    list_movie = []
    for item in movie_result:
        # print(item.get('a')['name']) 末日崩塌 关云长 夏日福星 惊天破
        name = item.get('a')['name']
        rate = float(item.get('a')['rate'])
        year = int(item.get('a')['year'])
        list_movie.append({'name': name, 'rate': rate, 'year': year})
        # dict_movie[name] = dict_movie_inside
    # 列表，后续的rate和year是用来加权求和来比较哪个电影好
    # {'name': '末日崩塌', 'rate': 7.0, 'year': 2015}, {'name': '关云长', 'rate': 5.0, 'year': 2011}
    # print(list_movie)
    # 寻找上下五年的top_5电影
    year_movie = [movie for movie in list_movie if movie['year'] >= (movie_year - 5) and movie['year'] <= (movie_year + 5)]
    top_5 = []
    # lambda函数用于从每个字典中提取rate值，并将其转换为浮点数进行比较
    sorted_movies = sorted(year_movie, key=lambda x: x['rate'], reverse=True)
    # 获取前5个元素作为top 5
    top_5_movies = sorted_movies[:5]
    # {'name': 'JOJO的奇妙冒险 星尘斗士 埃及篇', 'rate': 9.6, 'year': 2015}, {'name': '我们的父辈', 'rate': 9.6, 'year': 2013}
    # print(top_5_movies)
    return top_5_movies



# 示例
input_movie = '长津湖'
print(f"推荐给喜欢{input_movie}的观众：")
result = recommend_movie(input_movie)
# node_match(result)

